package com.sd365.gateway.core.filter;

import com.alibaba.nacos.client.utils.StringUtils;
import com.sd365.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhengjianjian
 * @version 1.0.0
 * @class MyTokenGatewayFilter
 * @classdesc 判断Token是否存在，转发到授权中心
 * @date 2020/12/18
 * @see
 * @since
 */
@Slf4j
@Component
public class MyTokenGatewayFilter implements GlobalFilter, Ordered {
    @Qualifier("queryToken")
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    private RestTemplate restTemplate;
    public static final String authorization_URL = "http://gateway-authorization";


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        log.info("进入全局过滤器");
        //获取请求路径
        String URI = exchange.getRequest().getURI().toString();
        log.info("请求的url：{}", URI);
        //是否鉴权成功
        Boolean flag = false;
        if (URI.contains("user/login")
                || URI.contains("user/info")
                || URI.contains("user/logout")
                || URI.contains("oms/order/v1/order")
                || URI.contains("/exchange/system/v1/systemapi/notify")) {
            return chain.filter(exchange);
        }
        List<String> accessToken = exchange.getRequest().getHeaders().get("accessToken");

        List<String> appkey = exchange.getRequest().getHeaders().get("appkey");

        String Token = null;
        String Appkey = null;
        if (!CollectionUtils.isEmpty(accessToken)) {
            Token = accessToken.toString();
        }
        if (!CollectionUtils.isEmpty(appkey)) {
            Appkey = appkey.toString();
        }
        if (!StringUtils.isEmpty(Token)) {
            try {
                log.info("发起restTemplate请求");
                flag = restTemplate.getForObject(authorization_URL + "/v1/authorization?token=" + Token + "&url=" + URI, Boolean.class);
                log.info("restTemplate请求结束");
            } catch (Exception ex) {
                log.info("请求异常", ex);
            }
            if (flag) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//回应
                return exchange.getResponse().setComplete();
            }
        } else if (StringUtil.isEmpty(Token)) {
            try {
                flag = restTemplate.getForObject(authorization_URL + "/v1/common/resource?&url=" + URI, Boolean.class);
            } catch (RestClientException ex) {
                log.info("请求异常", ex);
            }
            if (flag) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//回应
                return exchange.getResponse().setComplete();
            }

        } else if (!StringUtil.isEmpty(Appkey)) {
            try {
                flag = restTemplate.getForObject(authorization_URL + "/v1/common/resource?&url=" + URI, Boolean.class);
            } catch (RestClientException ex) {
                log.info("请求异常", ex);
            }
            if (flag) {
                return chain.filter(exchange);
            } else {
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//回应
                return exchange.getResponse().setComplete();
            }
        } else {
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//回应
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
